//
//  MSFormatTextField.m
//  JYG_Sales
//
//  Created by Mac_User on 15/10/27.
//  Copyright (c) 2015年 WeShare. All rights reserved.
//

#import "MSFormatTextField.h"


@interface MSFormatTextField () <UITextFieldDelegate>
{
    NSString *previousTextFieldContent;
    UITextRange *previousSelection;
}
@end
@implementation MSFormatTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.delegate = self;
        self.keyboardType = UIKeyboardTypeNumberPad;
        [self addTarget:self action:@selector(reformatAsCardNumber:)
       forControlEvents:UIControlEventEditingChanged];
    }

    return self;
}

- (void)reformatAsCardNumber:(UITextField *)textField
{
    NSUInteger targetCursorPosition =
    [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];

    NSString *cardNumberWithoutSpaces = [self removeNonDigits:textField.text andPreserveCursorPosition:&targetCursorPosition];

    if (self.fieldType == MSTextFieldType_BankCard) {
        if ([cardNumberWithoutSpaces length] > 19) {
            [textField setText:previousTextFieldContent];
            textField.selectedTextRange = previousSelection;
            return;
        }
    }

    if (self.fieldType == MSTextFieldType_PhoneNumber) {
        if ([cardNumberWithoutSpaces length] > 11) {
            [textField setText:previousTextFieldContent];
            textField.selectedTextRange = previousSelection;
            return;
        }
    }
    NSString *cardNumberWithSpaces = [self insertSpacesEveryFourDigitsIntoString:cardNumberWithoutSpaces andPreserveCursorPosition:&targetCursorPosition];
    textField.text = cardNumberWithSpaces;
    UITextPosition *targetPosition =
    [textField positionFromPosition:[textField beginningOfDocument]offset:targetCursorPosition];

    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition
     toPosition:targetPosition]];
}

- (BOOL)textField:(UITextField *)textField
        shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;

    if (self.fieldType == MSTextFieldType_PhoneNumber) {
        if(range.location==0) {
            if(string.integerValue >1)
            {
                return NO;
            }
        }
    }

    return YES;
}

- (NSString *)removeNonDigits:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition
{
    NSUInteger originalCursorPosition = *cursorPosition;
    NSMutableString * digitsOnlyString = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < [string length]; i++) {
        unichar characterToAdd = [string characterAtIndex:i];
        if (isdigit(characterToAdd)) {
            NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [digitsOnlyString appendString:stringToAdd];
        } else {
            if (i < originalCursorPosition) {
                (*cursorPosition)--;
            }
        }
    }

    return digitsOnlyString;
}
- (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string andPreserveCursorPosition :(NSUInteger *)cursorPosition
{
    NSMutableString * stringWithAddedSpaces = [[NSMutableString alloc] init];
    NSUInteger cursorPositionInSpacelessString = *cursorPosition;
    if (self.fieldType == MSTextFieldType_PhoneNumber) {
        for (NSUInteger i=0; i<string.length; i++) {
            if(i>0)
            {
                if(i==3 || i==7) {
                    [stringWithAddedSpaces appendString:@" "];

                    if(i<cursorPositionInSpacelessString) {
                        (*cursorPosition)++;
                    }
                }
            }
            unichar characterToAdd = [string characterAtIndex:i];
            NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [stringWithAddedSpaces appendString:stringToAdd];
        }
    }

    if (self.fieldType == MSTextFieldType_BankCard) {
        for (NSUInteger i = 0; i < [string length]; i++) {
            if ((i > 0) && ((i % 4) == 0)) {
                [stringWithAddedSpaces appendString:@" "];
                if (i < cursorPositionInSpacelessString) {
                    (*cursorPosition)++;
                }
            }
            unichar characterToAdd = [string characterAtIndex:i];
            NSString * stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [stringWithAddedSpaces appendString:stringToAdd];
        }
    }
    return stringWithAddedSpaces;
}
@end
